//
//  CZRefreshControl.swift
//  微博08
//
//  Created by apple on 16/3/4.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

/// 自定义下拉刷新控件
class CZRefreshControl: UIRefreshControl {
    
    // 箭头旋转的偏移值
    private let refreshControlOffest: CGFloat = -60
    
    /// 标示位
    private var isUp = false
    
    // 覆盖父类的属性
    // 添加override
    // 实现didSet
    override var frame: CGRect {
        didSet {
            if frame.origin.y > 0 {
                return
            }
            
            // 能到下面来y为负数
            // 0 - 60箭头向下
            // 小于-60,箭头向上
            if frame.origin.y <= refreshControlOffest && !isUp {
                isUp = true
                refreshView.rotationTipIcon(isUp)
            } else if frame.origin.y > refreshControlOffest && isUp {
                isUp = false
                refreshView.rotationTipIcon(isUp)
            }
            
            if refreshing {
                refreshView.startLoading()
            }

        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init() {
        super.init()
        
        prepareUI()
    }
    
    /**
     当tableView回到原来的位置时,结束刷新
     */
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopLoading()
    }
    
    private func prepareUI() {
        // 添加子控件
        addSubview(refreshView)
        
        
        // 添加约束
        refreshView.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(refreshView.frame.size)
            make.centerX.centerY.equalTo(self)
        }

        print("refreshView: \(refreshView.frame)")
    }
    
    // MARK: - 懒加载
    /// 刷新的自定义view,从xib里面加载出来的view,在xib里面设置有多大加载出来就有多大
    private lazy var refreshView: CZRefreshView = CZRefreshView.refreshView()
}
